import 'dart:convert';

import 'package:byw_blog/model/SetingBean.dart';
import 'package:byw_blog/network/NetworkInterface.dart';
import 'package:byw_blog/pages/HomePage.dart';
import 'package:byw_blog/utils/ConfigUtil.dart';
import 'package:byw_blog/widget/MyDialogWidget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart';
import 'package:intl/intl.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:webfeed/domain/rss_feed.dart';

class SetingPage extends StatefulWidget {
  const SetingPage({Key? key}) : super(key: key);

  @override
  State<SetingPage> createState() => _SetingPageState();
}

class _SetingPageState extends State<SetingPage> {
  final Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
  List<SetingBean> menus = [];

  @override
  void initState() {
    super.initState();
    initMenu();
  }

  initMenu() async {
    var as = await ConfigUtil.getArticleSource();
    var ia = await ConfigUtil.getInterfaceAddress();
    var xa = await ConfigUtil.getXmlAddress();
    setState(() {
      menus = [
        SetingBean(menuName: "数据来源", menuValue: as, dialogHintText: ""),
        SetingBean(menuName: "接口地址", menuValue: ia, dialogHintText: "请输入接口地址"),
        SetingBean(menuName: "订阅地址", menuValue: xa, dialogHintText: "请输入订阅地址"),
      ];
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),
        title: const Text("设置"),
        actions: [
          IconButton(
              onPressed: () {
                saveUrl();
              },
              icon: const Icon(Icons.save))
        ],
      ),
      body: Padding(
        padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
        child: Stack(
          children: List.generate(menus.length, (index1) {
            return ListView.builder(
                itemCount: menus.length,
                itemBuilder: (context, index2) {
                  return Container(
                    alignment: Alignment.topLeft,
                    padding: const EdgeInsets.symmetric(
                        horizontal: 10, vertical: 10),
                    child: InkWell(
                      onTap: () => {
                        // 点击列表事项
                        showDialog(
                          context: context,
                          builder: (context) {
                            if (index2 == 0) {
                              return MyDialogWidget.showListDialog(
                                  context, ["VanBlog"], (value) {
                                ConfigUtil.setArticleSource(value);
                                initMenu();
                              });
                            } else {
                              return MyDialogWidget.showInputDialog(
                                  context,
                                  menus[index2].menuName,
                                  menus[index2].menuValue!,
                                  menus[index2].dialogHintText!, (value) {
                                if (index2 == 1) {
                                  ConfigUtil.setInterfaceAddress(value);
                                } else if (index2 == 2) {
                                  ConfigUtil.setXmlAddress(value);
                                }
                                initMenu();
                              });
                            }
                          },
                        )
                      },
                      child: Column(
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(menus[index2].menuName!,
                                  style: const TextStyle(fontSize: 16),
                                  overflow: TextOverflow.ellipsis,
                                  textAlign: TextAlign.left),
                              Text(
                                menus[index2].menuValue!,
                                style: const TextStyle(
                                    fontSize: 14, color: Colors.grey),
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                textAlign: TextAlign.end,
                              ),
                            ],
                          ),
                          const SizedBox(
                            height: 10,
                          ),
                          const Divider(
                            height: 1.0,
                            indent: 0,
                            color: Colors.grey,
                          ),
                        ],
                      ),
                    ),
                  );
                });
          }),
        ),
      ),
    );
  }

  /// 将博客数据拉下来，提交到数据库
  saveUrl() async {
    var address = await ConfigUtil.getXmlAddress();
    final response = await get(Uri.parse(address));
    var channel = RssFeed.parse(Utf8Codec().decode(response.bodyBytes));
    setState(() {
      HomePage.rss = channel.items;
      addBlog();
    });
  }

  void addBlog() {
    HomePage.rss?.forEach((element) {
      int start = element.author!.lastIndexOf('(') + 1;
      int end = element.author!.lastIndexOf(')');
      var author = element.author?.substring(start, end);
      String categorie ="";
      element.categories?.forEach((element) {
        categorie = element.value;
      });
      var format = DateFormat('MMM dd')
          .format(DateTime.parse(element.pubDate.toString()));
      String description = "";
      if(element.description == null){
        description = "";
      }
      NetworkInterface.addBlog(element.title!, author!, element.link!, categorie, format,description,element.content?.value as String).then((value) => {
        // 添加结果
        value.toString()
      });
      return;
    });
  }
}
